path = require 'path'
klaw = require('klaw')
glob = require( 'glob' )
util = require('util')
fs = require('fs-extra')
glob = util.promisify(require('glob'))
{basename} = require 'path'
klawSync = require('klaw-sync')

_require = (path)->
    try
        return require("../url/"+path)
    catch err
        console.trace(err)
        console.log "加载出错 #{path} \n"

module.exports = (app)->
    dirname = path.resolve(__dirname, '../url')
    dirname_len = dirname.length+1
    dir_li = []

    route = new require('koa-router')()
    for item in klawSync(dirname)
        path = item.path.slice(dirname_len)
        if not path
            continue
        if item.stats.isDirectory()
            dir_li.push path
        else if path.endsWith('.coffee')
            if not basename(path).startsWith("_")
                m = _require(path)
                prefix = path.slice(0,-7)
                if prefix.endsWith("/index")
                    prefix = prefix.slice(0, -6)
                route.use("/#{prefix}/", m.routes(), m.allowedMethods())

    app.use(route.routes()).use(route.allowedMethods())


